package com.borderbears.backend.media;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import nanoxml.XMLElement;


public class MediaNode {


	private final XMLElement xml;

	private List<MediaNode> children;

	private MediaType mediaType;

	public MediaNode(final XMLElement xml) {
		this.xml = xml;
	}

	public XMLElement getXML() {
		return xml;
	}

	public List<MediaNode> getChildren() {
		if (null == children) {
			createChildren();
		}
		return children;
	}

	public MediaType getMediaType() {
		if (null == mediaType) {
			mediaType = MediaManager.getInstance().detectMediaType(this);
		}
		return mediaType;
	}

	public boolean isDirectory() {
		return "directory".equals(xml.getName());
	}

	public URL getURL() {
		try {
			final String url = xml.getStringAttribute("url");
			if (null != url) {
				return new URL(url);
			}
		} catch (final MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}


	@SuppressWarnings("unchecked")
	private void createChildren() {
		final Vector<XMLElement> xmlChildren = xml.getChildren();
		children = new ArrayList<MediaNode>();
		for (final XMLElement x : xmlChildren) {
			if ("meta".equals(x.getName())) {
				//
			} else {
				children.add(new MediaNode(x));
			}
		}
	}

	@Override
	public String toString() {
		return xml.getStringAttribute("name");
	}


}
